package com.yenlien.traceyun.control.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.control.bean.RestURL;
import com.yenlien.traceyun.control.controller.form.ModelCropForm;
import com.yenlien.traceyun.control.dao.*;
import com.yenlien.traceyun.control.entity.*;
import com.yenlien.traceyun.control.interceptor.UserAuthUtil;
import com.yenlien.traceyun.control.service.rest.AppRestService;
import com.yenlien.traceyun.control.service.rest.FileRestService;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by LiuSha on 2020/3/24.
 */
@Service
public class ModelCropService {
    @Autowired
    private ModelCropDao modelCropDao;
    @Autowired
    private CropService cropService;
    @Autowired
    private BirthService birthService;
    @Autowired
    private ModelClassifyDao modelClassifyDao;
    @Autowired
    private FileRestService fileRestService;
    @Autowired
    private ModelClassifyService modelClassifyService;
    @Autowired
    private JdbcTemplate jdbc;
    @Autowired
    private CompanyCropDao companyCropDao;
    @Autowired
    private AppRestService appRestService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CompanyModelClassifyDao companyModelClassifyDao;

    @Autowired
    private ModelCategoryService modelCategoryService;

    @Autowired
    private ModelCategoryDao modelCategoryDao;

    @Autowired
    private BirthDao birthDao;

    @Autowired
    private CropDao cropDao;

    /**
     * 查询
     *
     * @param categoryId
     * @param companyId
     * @param name
     * @return
     */
    public List<ModelCrop> search(String categoryId, String companyId, String name) {

        List<ModelCategory> modelCategoryList = modelCategoryDao.findAll();
        List<ModelCategory> start = new ArrayList<>();
        if (StringUtils.isEmpty(categoryId)) {
            start.addAll(modelCategoryDao.findRootByCompanyId(companyId));
        } else {
            start.add(modelCategoryService.load(categoryId));
        }
        List<String> categoryIds = new ArrayList<>();
        modelCategoryService.parseIds(start, categoryIds, modelCategoryList);
        if (name == null) {
            name = "";
        }
        List<ModelCrop> modelCrops = modelCropDao.findByCategoryIds(categoryIds, name);
        return modelCrops;
    }

    /**
     * 获取父分类ids
     *
     * @param modelCrop
     * @return
     */
    public List<String> getCategoryTree(ModelCrop modelCrop) {
        List<String> parentIds = new ArrayList<>();
        String categoryId = modelCrop.getCategoryId();
        modelCategoryService.getParentIds(categoryId, parentIds);
        return parentIds;
    }


    /**
     * 根据分类加载作物
     *
     * @param categoryId
     * @return
     */
    public List<ModelCrop> findByCategoryId(String categoryId) {
        ModelCategory modelCategory = modelCategoryService.load(categoryId);
        List<ModelCategory> modelCategoryList = modelCategoryDao.findAll();
        List<ModelCategory> start = new ArrayList<>();
        start.add(modelCategory);
        List<String> categoryIds = new ArrayList<>();
        modelCategoryService.parseIds(start, categoryIds, modelCategoryList);
        List<ModelCrop> modelCrops = modelCropDao.findByCategoryIdInAndCompanyIdIsNull(categoryIds);
        return modelCrops;
    }

    public List<ModelCrop> getByCategoryId(String categoryId) {
        return modelCropDao.getByCategoryId(categoryId);
    }

    public List<ModelCrop> getParentBind(String categoryId) {
        // 当前登录用户的企业ID
        String parentId = modelCropDao.getParentId(UserAuthUtil.getLoginUser().getCompanyId());
        if ("1".equals(parentId)) {
            // 超管
            ModelCategory modelCategory = modelCategoryService.load(categoryId);
            List<ModelCategory> modelCategoryList = modelCategoryDao.findAll();
            List<ModelCategory> start = new ArrayList<>();
            start.add(modelCategory);
            List<String> categoryIds = new ArrayList<>();
            modelCategoryService.parseIds(start, categoryIds, modelCategoryList);
            List<ModelCrop> modelCrops = modelCropDao.findByCategoryIdInAndCompanyIdIsNull(categoryIds);
            return modelCrops;
        } else {
            // 查找上级政管绑定的基源
            return modelCropDao.getJy(parentId, categoryId);
        }
    }

    /**
     * 保存修改作物
     *
     * @param form
     * @param files
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ModelCrop save(ModelCropForm form, List<MultipartFile> files) throws Exception {

        if (form.getModelCrop().getId() != null) {
//            fileRestService.upload(modelCategoryDao.findById(form.getModelCrop().getId()).get(),form.getModelCrop(),files);
            // 解决基源修改报错Bug  2021-04-26  原本写法是上面注释的且没有下面的companyId设置
            fileRestService.upload(modelCategoryDao.findById(form.getModelCrop().getCategoryId()).get(), form.getModelCrop(), files);
        } else {
            fileRestService.upload(null, form.getModelCrop(), files);
        }
        // 解决基源修改报错Bug  2021-04-26
        if (org.apache.commons.lang3.StringUtils.isBlank(form.getModelCrop().getCompanyId())) {
            form.getModelCrop().setCompanyId(null);
        }
        ModelCrop modelCrop = modelCropDao.save(form.getModelCrop());
        List<Birth> births = form.getBirths();
        List<Crop> crops = form.getCrops();
        if (births != null && births.size() > 0) {
            birthService.saves(births, modelCrop.getId());
        }
        if (crops != null && crops.size() > 0) {
            cropService.saves(crops, modelCrop.getId(), files);
        }
        return modelCrop;

    }

    /**
     * 删除集合
     *
     * @param ids
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleIds(List<String> ids) {
        modelCropDao.deleteByIdIn(ids);
        birthDao.deleteByModelIdIn(ids);
        cropDao.deleteByModelIdIn(ids);
    }

    public void delteByCategoryId(String categoryId) {
        List<String> categryIds = new ArrayList<>();
        categryIds.add(categoryId);
        List<String> ids = modelCropDao.findIdsByCategoryIdIn(categryIds);
        deleIds(ids);
    }


    /**
     * 绑定or解绑
     *
     * @param companyId
     * @param modelCropId
     * @param appId
     * @param bind        1绑定，0解绑
     */
    public void bindone(String companyId, String modelCropId, String appId, String bind) {
        // 获取该企业类型，如果该企业的类型是政企，那么就有品种限制
//        String companyType = (String) restTemplate.getForObject(RestURL.USERCENTER + "/company/findTypeById/" + companyId, JSONObject.class).get("data");
//        if(org.apache.commons.lang3.StringUtils.isBlank(companyType)){
//            throw new BusinessException("该企业不存在");
//        }
//        if("2".equals(companyType)){
//
//        }
        //解绑
        if (bind.equals("0")) {
            companyCropDao.deleteByModelIdAndCompanyIdAndAppId(modelCropId, companyId, appId);
        } else if (bind.equals("1")) {
            LinkedHashMap map = (LinkedHashMap) restTemplate.getForObject(RestURL.USERCENTER + "app/getCompanyCustomAppVersion/" + companyId, JSONObject.class).get("data");
            // 获取该政管配置的政府监管产品的最大企业数
            if (map != null) {
                int modelNumMax = Integer.valueOf(map.get("modelNum").toString());
                // 获取该企业已有的品种数
                int count = companyCropDao.getCountByCompanyId(companyId);
                if (count >= modelNumMax) {
                    throw new BusinessException("该政管的品种数已达最大, 不能再选择。最多限制数量: " + modelNumMax + ", 已选择的品种数量: " + count);
                }
            }
            if (companyCropDao.findByModelIdAndCompanyIdAndAppId(modelCropId, companyId, appId) != null) {
                throw new BusinessException("500", "已绑定，请不要重复绑定");
            }
            CompanyCrop companyCrop = new CompanyCrop();
            companyCrop.setCompanyId(companyId);
            companyCrop.setModelId(modelCropId);
            companyCrop.setAppId(appId);
            companyCropDao.save(companyCrop);
        } else {
            throw new BusinessException("500", "bind只能是0或1,0解绑1绑定");
        }
    }

    /**
     * 加载已绑定的
     *
     * @param companyId
     * @param appId
     */
    public List<ModelCrop> loadBinded(String companyId, String appId) {
        // 修改后：如果companyId查不到，则用parentId去查询(如果有上级政管)，
//        if(StringUtils.isEmpty(appId)){
//            List<ModelCrop> modelCrops = modelCropDao.findByCompanyId(companyId);
//            // 查找上级(政管)
//            String parentId = modelCropDao.getParentId(companyId);
//            if("1".equals(parentId)){
//                return modelCrops;
//            }
//            List<ModelCrop> parentList = modelCropDao.findByCompanyId(parentId);
//
//            if(modelCrops == null || modelCrops.size() == 0){
//                // 查找上级(政管)
//                return modelCropDao.findByCompanyId(parentId);
//            }
//            return modelCrops;
//        }else{
//            List<ModelCrop> modelCrops = modelCropDao.findByCompanyIdAndAppId(companyId, appId);
//            if(modelCrops == null || modelCrops.size() == 0){
//                // 查找上级(政管)
//                String parentId = modelCropDao.getParentId(companyId);
//                if("1".equals(parentId)){
//                    // 这种就是没有政管， 直接拿中控产品配置的种类
//                    modelCategoryService.loadRootByCompanyId(companyId);
//                    return null;
//                }else {
//                    return modelCropDao.findByCompanyIdAndAppId(parentId, appId);
//                }
//            }
//            return modelCrops;
//        }

        if (StringUtils.isEmpty(appId)) {
            return modelCropDao.findByCompanyId(companyId);
        } else {
            return modelCropDao.findByCompanyIdAndAppId(companyId, appId);
        }
    }

    /**
     * 加载产出物
     *
     * @param modelId
     * @return
     */
    public List<Crop> loadCrop(String modelId) {
        return cropDao.findByModelId(modelId);
    }


    /**
     * 加载产出物
     *
     * @param
     * @return
     */
    public Crop addCrop(Crop crop) {
        return cropDao.save(crop);
    }


    /**
     * 分隔
     **************************************************************/


    @Transactional
    public void save(ModelCrop modelCrop, List<MultipartFile> files) throws Exception {
        fileRestService.upload(null, modelCrop, files);


    }


    public Object findById(String id) {
        ModelCrop modelCrop = modelCropDao.findById(id);
        return modelCrop;
    }

    public Object findByOneId(String id) {
//        return modelCropDao.findByOneId(id);
        return null;
    }


    public Object findByTwoId(String id) {
//        return modelCropDao.findByTwoId(id);
        return null;
    }


    public List<JSONObject> findByCompany(String companyId, String appId) {
        List<JSONObject> jsonObjectList = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("select * from t_company_crop where company_id='" + companyId + "'");
        sql.append(" and app_id='" + appId + "'");
        SqlRowSet rowSet = jdbc.queryForRowSet(sql.toString());
        while (rowSet.next()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", rowSet.getString("model_id"));
            jsonObject.put("name", rowSet.getString("name"));
            jsonObjectList.add(jsonObject);
        }
        return jsonObjectList;
    }

    public void saveCompanyModel(JSONObject object) {
        CompanyCrop companyCrop = JSONObject.toJavaObject(object, CompanyCrop.class);
        JSONObject param = new JSONObject();
        param.put("appId", object.getString("appId"));
        param.put("companyId", object.getString("companyId"));
        JSONObject jsonObject = appRestService.findCompanyCustomAppVersion(param);
        if (jsonObject != null) {
            String modelNum = jsonObject.getString("modelNum");
            List<JSONObject> jsonObjects = findByCompany(companyCrop.getCompanyId(), companyCrop.getAppId());
            if (jsonObjects.size() > 0 && modelNum != null) {
                Integer num = Integer.parseInt(modelNum);
                if (num > 0 && jsonObjects.size() == num) {
                    throw new BusinessException("超出基源范围，您只能选择" + modelNum + "种");
                }
            }
            companyCrop.setName(modelCropDao.getByName(companyCrop.getModelId()));
            companyCropDao.save(companyCrop);
        }
    }

    public void deleteCompanyModel(String modelId, String companyId) {
        CompanyCrop companyCrop = companyCropDao.findByModelIdAndCompanyId(modelId, companyId);
        companyCropDao.delete(companyCrop);
    }

    @Transactional
    public void delecrop(String modelcropId) {
        modelCropDao.deleteById(modelcropId);
        cropDao.deleteByModelId(modelcropId);
        birthDao.deleteByModelId(modelcropId);
    }


}
